/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller.CoreServlet;

import Controller.CoreServlet.Ultility.SSCookie_Login;
import Model.BeanUltility.ResourceMapper;
import Model.BeanUltility.ResultsetMapper;
import Model.DataUltility.DatabaseConnector;
import Model.ObjectBean.ViewBean.LoginStatus;
import Model.ObjectBean.ViewBean.PersonalInfo_FrDatabase;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Tran Nguyen Anh Tu
 */
public class SearchServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        LoginStatus status = new LoginStatus();
        status.setStatus("false");
        PersonalInfo_FrDatabase perInfo=new PersonalInfo_FrDatabase();
        
          
        if(req.getCookies()!=null && SSCookie_Login.check_cookieLoginInfo(req,1,"logged"))
        {
            status.setStatus("true");
            
            perInfo.setFirstname(SSCookie_Login.get_cookieInfo(req,"perInf"));
        }
        

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        

        String querry;
        String page=req.getParameter("p");
        ArrayList result=new ArrayList();
             
        //If page is null, mean that this page is fresh page, and need an init process
        //1. When receive an req with search condition, the program will pass req to alanyze function
        //  Analyzing will return a completed querry string. For more information, look at analyzeRequestQuerry
        //2. Then, search in database with querry string, return a resulset.
        //3. Map resultset into an array, then put that array into session, then foward to content.jsp
        //If page is not null, mean that this page already have had a result array, so this page only need a page number
        //to point the right item for displaying
        if(page==null)
        {
            result=ResourceMapper.getResourceList(req);        
            req.getSession().setAttribute("result", result);
            req.setAttribute("p", 1);
        }
        else
            req.setAttribute("p", page);
        req.setAttribute("author", req.getParameter("author"));
        req.setAttribute("iname", req.getParameter("iname"));
        RequestDispatcher dispatcher = req.getRequestDispatcher("/MainPages/itemlisting.jsp");
        dispatcher.forward(req, resp);
    }
}
